import random
import time
import math

import pyautogui

from pynput.mouse import Button, Controller

mouse = Controller()


def virtual_click(x, y, button=Button.left, click_count=2):
    original_position = mouse.position
    mouse.position = (x, y)
    for _ in range(click_count):
        mouse.click(button)
    mouse.position = original_position


pyautogui.PAUSE = 0.3


def color_distance(color1, color2):
    return math.sqrt(sum((c1 - c2) ** 2 for c1, c2 in zip(color1, color2)))


def closest_color(pixel_color, colors):
    distances = {color: color_distance(pixel_color, color) for color in colors}
    return min(distances, key=distances.get)


def euclidean_distance(point1, point2):
    return math.sqrt((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2)


def if_match_image(image_path, confidence):
    try:
        location = pyautogui.locateOnScreen(image_path, confidence=confidence)
        return location is not None
    except Exception as e:
        print(e)
        return False


def cluster_locations(locations, distance_threshold=100):
    clusters = []
    for location in locations:
        added_to_cluster = False
        for cluster in clusters:
            if any(euclidean_distance(location, point) < distance_threshold for point in cluster):
                cluster.append(location)
                added_to_cluster = True
                break
        if not added_to_cluster:
            clusters.append([location])
    return clusters


def count_ur():
    positions = []
    # r的颜色
    r_color = (240, 240, 240)
    # sr的颜色
    sr_color = (234, 210, 248)
    # ur的颜色
    ur_color = (218, 144, 240)
    ur_count, sr_count, r_count = 0, 0, 0
    for i in range(10):
        x = round(1121 / 9 * i) + 800
        positions.append((x, 900))
    
    for x, y in positions:
        pixel_color = pyautogui.pixel(x, y)
        closest = closest_color(pixel_color, [r_color, sr_color, ur_color])
        if closest == ur_color:
            ur_count += 1
        elif closest == sr_color:
            sr_count += 1
        else:
            r_count += 1
    
    print('ur:{} sr:{} r:{}'.format(ur_count, sr_count, r_count))
    
    return ur_count, sr_count, r_count


def locate_multiple_images(image_paths, confidence):
    for path in image_paths:
        
        if confidence is None:
            location = pyautogui.locateOnScreen(path,grayscale=True)
        else:
            location = pyautogui.locateOnScreen(path, confidence=confidence, grayscale=True)
        if location is not None:
            return location
        
    return None


def click_once(paths, confidence, click_count=1):
    try:
        buttonLocation = locate_multiple_images(paths, confidence)
        if buttonLocation is not None:
            button_x, button_y = pyautogui.center(buttonLocation)
            offset_x = random.randint(-5, 5)
            offset_y = random.randint(-5, 5)
            for i in range(click_count):
                pyautogui.leftClick(button_x + offset_x, button_y + offset_y)
            return True
    except pyautogui.ImageNotFoundException:
        print('没有找到图片')
        return False


def click_until_found(path, retries=100, confidence=None, click_count=1):
    attempts = 0
    while attempts < retries:
        if click_once(path, confidence, click_count):
            return
        time.sleep(0.3)
        attempts += 1
    raise pyautogui.ImageNotFoundException('超过最大尝试次数')


if __name__ == '__main__':
    screen_width, screen_height = pyautogui.size()
    print(screen_width, screen_height)
    
    # 记录循环次数
    count = 0
    while True:
        print('第{}次抽卡'.format(count))
        # 1. 点击抽卡按钮
        click_until_found(['../images/gacha.png'], confidence=0.9)
        # 2. 点击抽卡确认按钮
        click_until_found(['../images/confirm.png'], click_count=1)
        # pyautogui.press('enter')
        time.sleep(2)
        # 3. 点击skip按钮
        # click_until_found(['../images/skip_ur.png', '../images/skip_no_ur.png', '../images/skip.png'], click_count=8)
        
        pyautogui.click(2164,231)
        
        pyautogui.click(2164,231)
        pyautogui.click(2164,231)
        pyautogui.click(2164,231)
        pyautogui.click(2164,231)
        pyautogui.click(2164,231)
        # 4. 判断是否有需要的角色 TODO
        time.sleep(2)
        ur = 0
        # for i in range(3):
        #
        #     ur_count, _, _ = count_ur()
        #     ur = max(ur, ur_count)
        #     time.sleep(0.5)
        # if ur >= 2:
        #     print('抽到了两个UR')
        #     if if_match_image('../images/ironMask.png', 0.95):
        #         print('抽到了铁面')
        #         break
        #     break
        try:
            ur = len(list(pyautogui.locateAllOnScreen('../images/5.png', grayscale=True, confidence=0.9)))
        except Exception as e:
            print(e)
        print('ur:', ur)
        if ur >= 3:
            print('抽到了三个UR')
            break
        # 5. 没有就继续循环
        count += 1
        
        time.sleep(2)
